package hk.ust.comp3111.ustnutrition.data;

import java.util.Iterator;
import java.util.List;

import com.couchbase.lite.DocumentChange;
import com.couchbase.lite.QueryEnumerator;
import com.couchbase.lite.QueryRow;

public interface DataTableListener<T extends DataRow> {
	public static class ChangeEvent<T extends DataRow> implements Iterable<T> {
		public ChangeEvent(DataTable<T> table, com.couchbase.lite.LiveQuery.ChangeEvent event) {
			this.event = event;
			this.table = table;
		}
		
		public ChangeEvent(DataTable<T> table,
				com.couchbase.lite.Database.ChangeEvent event2) {
			this.event2 = event2;
			this.table = table;
		}

		DataTable<T> table;
		com.couchbase.lite.LiveQuery.ChangeEvent event;
		com.couchbase.lite.Database.ChangeEvent event2;

		public Iterator<T> iterator() {
			if(event != null) {
				final QueryEnumerator rows = event.getRows();
				return new Iterator<T>() {
					
					@Override
					public boolean hasNext() {
						return rows.hasNext();
					}
	
					@Override
					public T next() {
						QueryRow row = rows.next();
						return table.get(row.getDocumentId());
					}
	
					@Override
					public void remove() {
						rows.remove();
					}
	
				};
			} else {
				final Iterator<DocumentChange> rows = event2.getChanges().iterator();
				return new Iterator<T>() {
					
					@Override
					public boolean hasNext() {
						return rows.hasNext();
					}
	
					@Override
					public T next() {
						DocumentChange row = rows.next();
						return table.get(row.getDocumentId());
					}
	
					@Override
					public void remove() {
						rows.remove();
					}
	
				};
			}
		}
	}
	
	void changed(ChangeEvent<T> event);
}
